import { reactive } from 'vue';
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus';
 export const setup = () => {
  const options = reactive({
    upFileNamber: 0,
    fileList: [], // 上传文件列表
    isUpdata: false, // 上传成功
    loading: false,
  });
  const methods = {
    // 上传文件：之前
    handleBeforeUpload(file) {
      let isUpdata = true;
      options.loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      isUpdata ? options.upFileNamber++ : '';
      if (options.upFileNamber === 0) {
        options.loading.close();
      } 
      return isUpdata;
    },
    // 上传文件:成功
    handleSeccess(res, file, fileList) {
      // if (options.upFileNamber === fileList.length) {
      //   options.loading.close();
      // }
      options.loading.close();
      if (res.code === 200) {
        if (res.data) {
          file.attachId = res.data.attachId;
          file.attachUrl = res.data.attachUrl;
        }
        file.res = res;
        options.fileList = reactive(fileList);
      } else {
        ElMessage.error('文件上传失败');
      }
    },
    // 上传文件:失败
    handlError(err, file, fileList) {
      options.upFileNamber--;
      const length = fileList.length && fileList.length !== 'undefined' ? fileList.length : 0;
      if (options.upFileNamber === length) {
        options.loading.close();
      }
      ElMessage.info('文件上传失败');
    },
    // 上传文件:删除文件
    handleRemove(file, fileList) {
      options.fileList = reactive(fileList);
      options.upFileNamber--;
      if (options.upFileNamber === fileList.length) {
        options.loading.close();
      }
    },
    // 移除文件前
    beforeRemove(file) {
      return ElMessageBox.confirm(`确定移除 【${file.name}】？`);
    },
  };
  return { options, methods };
};
